package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class WorkspaceServiceImpl implements WorkspaceService {

	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private DishMapper dishMapper;
	@Autowired
	private SetmealMapper setmealMapper;

	@Override
	public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
		Map<String, Object> map = new HashMap<>();
		map.put("begin", begin);
		map.put("end", end);
		//查询总订单数
		Integer totalOrderCount = orderMapper.countByMap(map);
		//查询营业额
		map.put("status", Orders.COMPLETED);
		Double turnover = orderMapper.sumByMap(map);
		turnover = turnover == null ? 0.0 : turnover;
		//查询有效订单数
		Integer validOrdersCount = orderMapper.countByMap(map);
		//查询订单完成率及平均客单价
		Double orderCompletionRate = 0.0;
		Double unitPrice = 0.0;
		if (totalOrderCount != null && validOrdersCount != null) {
			//订单完成率
			orderCompletionRate = validOrdersCount.doubleValue() / totalOrderCount.doubleValue();
			//平均客单价
			unitPrice = turnover / validOrdersCount;
		}
		//查询新增用户数
		Integer newUsers = orderMapper.countByMap(map);

		return BusinessDataVO.builder().turnover(turnover).validOrderCount(validOrdersCount).orderCompletionRate(orderCompletionRate).unitPrice(unitPrice).newUsers(newUsers).build();
	}

	@Override
	public OrderOverViewVO overviewOrders() {
		Map<String, Object> map = new HashMap<>();
		map.put("begin", LocalDateTime.now().with(LocalTime.MIN));
		map.put("end", LocalDateTime.now().with(LocalTime.MAX));
		//全部订单 数
		Integer allOrders = orderMapper.countByMap(map);
		//待接单数
		map.put("status", Orders.TO_BE_CONFIRMED);
		Integer waitingOrders = orderMapper.countByMap(map);
		//待派送单数
		map.put("status", Orders.CONFIRMED);
		Integer deliveredOrders = orderMapper.countByMap(map);
		//已完成数
		map.put("status", Orders.COMPLETED);
		Integer completedOrders = orderMapper.countByMap(map);
		//已取消数
		map.put("status", Orders.CANCELLED);
		Integer cancelledOrders = orderMapper.countByMap(map);
		return OrderOverViewVO.builder()
				.waitingOrders(waitingOrders)
				.deliveredOrders(deliveredOrders)
				.completedOrders(completedOrders)
				.cancelledOrders(cancelledOrders)
				.allOrders(allOrders)
				.build();
	}

	@Override
	public DishOverViewVO overviewDishes() {
		return dishMapper.queryStatusCount();
	}

	@Override
	public SetmealOverViewVO overviewSetmeals() {
		return setmealMapper.queryStatusCount();
	}
}
